package com.cloud.mkz.admin.util;

import cn.hutool.core.collection.CollectionUtil;
import com.cloud.mkz.admin.api.dto.RoleMenuDto;
import com.cloud.mkz.admin.mapper.RbacRoleMenuMapper;
import com.cloud.mkz.core.common.constant.CacheConstants;
import com.cloud.mkz.core.common.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class InitRbacUtil {
    private final RbacRoleMenuMapper rbacRoleMenuMapper;
    private final RedisUtil redisUtil;

    /**
     * 服务启动时加载系统参数
     */
    @PostConstruct
    public void init(){
        initRbacData();
    }

    /**
     * 初始化系统参数
     */
    public boolean initRbacData(){
        boolean result = true;
        try {
            //初始化系统角色菜单关系缓存
            Map<String, List<RoleMenuDto>> roleMenuMap = new HashMap<>(16);
            List<RoleMenuDto> allRoleMenus = rbacRoleMenuMapper.getRoleMenuInfo();
            if(CollectionUtil.isNotEmpty(allRoleMenus)){
                List<RoleMenuDto> tempRoleMenuList = null;
                String temp = "-9";
                for(RoleMenuDto roleMenuInfo : allRoleMenus) {
                    if(!roleMenuInfo.getRoleId().toString().equals(temp)){
                        if(!"-9".equals(temp)){
                            roleMenuMap.put(temp, tempRoleMenuList);
                        }
                        tempRoleMenuList = new ArrayList<>();
                        temp = roleMenuInfo.getRoleId().toString();
                    }
                    tempRoleMenuList.add(roleMenuInfo);
                }
                roleMenuMap.put(temp, tempRoleMenuList);
            }
            redisUtil.set(CacheConstants.SYSTEM_ROLE_MENU_AUTH_DATA, roleMenuMap);
        }catch (Exception e) {
            result = false;
        }
        return result;
    }
}
